#include "SpriteButton.h"

using namespace cocos2d;

CSpriteButton::CSpriteButton(void)
{
	m_pframeList = NULL;
	m_nStatus = SB_IMAGE_NORMAL;
	m_pListener = NULL;
	m_pfnSelector = NULL;
}

CSpriteButton::~CSpriteButton(void)
{
	CC_SAFE_DELETE_ARRAY(m_pframeList);
}

void CSpriteButton::initWithTexture(const char *pszFilename, int fWidth, int fHeight, CCObject *pTarget, SEL_SBHandler selector)
{
	CCSprite::init();
	CC_SAFE_DELETE_ARRAY(m_pframeList);
	m_pframeList = new CCArray;

	//Texture load with Cache
	CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage(pszFilename);;

	for( int i = 0; i < 2; i++ )
	{
		CCSpriteFrame *frame = CCSpriteFrame::createWithTexture(texture,
			CCRectMake(fWidth*i, fHeight*0, fWidth, fHeight) );
		m_pframeList->addObject(frame);
	}
	m_nStatus = SB_IMAGE_NORMAL;
	setDisplayFrame((CCSpriteFrame *)m_pframeList->objectAtIndex(m_nStatus));
	m_pListener = pTarget;
	m_pfnSelector = selector;
}

void CSpriteButton::initWithFrame(CCSpriteFrame *fNormal, CCSpriteFrame *fSelected, CCObject *pTarget, SEL_SBHandler selector)
{
	CCSprite::init();
	CC_SAFE_DELETE_ARRAY(m_pframeList);
	m_pframeList = new CCArray;

	m_pframeList->addObject(fNormal);
	m_pframeList->addObject(fSelected);

	m_nStatus = SB_IMAGE_NORMAL;
	setDisplayFrame((CCSpriteFrame *)m_pframeList->objectAtIndex(m_nStatus));
	m_pListener = pTarget;
	m_pfnSelector = selector;
}

CCRect CSpriteButton::rect(void)
{
	float x = this->getPositionX();
	float y = this->getPositionY();
	float anchorX = this->getAnchorPoint().x;
	float anchorY = this->getAnchorPoint().y;
	float w = this->getContentSize().width;
	float h = this->getContentSize().height;

    return CCRectMake( x - w * anchorX,
                      y - h * anchorY,
                      w, h);
}

bool CSpriteButton::IsTouchInRect(CCTouch *touch)
{
	CCRect rc = rect();
	rc.origin = CCPointZero;
	CCPoint pnt = convertTouchToNodeSpace(touch);
	return rc.containsPoint(pnt);
}

void CSpriteButton::onTouchBeganHandler(void)
{
	m_nStatus = SB_IMAGE_SELECTED;
	setDisplayFrame((CCSpriteFrame *)m_pframeList->objectAtIndex(m_nStatus));
	if (m_pListener && m_pfnSelector)
	{
		(m_pListener->*m_pfnSelector)(this, SB_TOUCH_BEGAN);
	}
}

void CSpriteButton::onTouchEndedHandler(void)
{
	m_nStatus = SB_IMAGE_NORMAL;
	setDisplayFrame((CCSpriteFrame *)m_pframeList->objectAtIndex(m_nStatus));
	if (m_pListener && m_pfnSelector)
	{
		(m_pListener->*m_pfnSelector)(this, SB_TOUCH_ENDED);
	}
}

